//
//  DetailImageView.m
//  Mooker
//
//  Created by hua zhang on 3/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DetailImageView.h"
#import <QuartzCore/CALayer.h>
#import "LolayGridView.h"
#import "MKImageView.h"
#import "Util.h"

#define kImageListLeftMargin  70
#define kMaxImageListHeight   125
#define kGridViewCellWidth    35

#define kImageSwitchInterval  4

#define kImageViewDefaultHeight 180

#define kSideMargin     8

#define kDefaultBottomBarHeight 38

@interface DetailImageView () <UIScrollViewDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
{
    BOOL _isAnimating;
//    BOOL _isFromSubject;    //是否为专题内组图
    UIInterfaceOrientation _curOrientation;
}
@property (nonatomic, retain) PicModel  *picture;
@property (nonatomic, retain) NSArray  *datasource;
@property (nonatomic, retain) UIScrollView *imageSrollView;
@property (nonatomic, retain) MKImageView  *imageView;
@property (nonatomic, retain) UIScrollView *infoScrollView;

@property (nonatomic, retain) UIView    *menuView;
@property (nonatomic, assign) NSInteger curSelectedImageIndex;
@property (nonatomic, retain) NSTimer   *timer;

@property (nonatomic, retain) UIImageView *colorHeadImage;

@property (nonatomic, retain) UIImageView *bgImageViewCount;
@property (nonatomic, retain) UILabel *labelCount;

- (void)backButtonTapped:(id)sender;
- (void)downloadButtonTapped:(id)sender;
- (void)playButtonTapped:(id)sender;
- (void)forwardButtonTapped:(id)sender;
- (void)resetImageViewSize;
- (void)handleTapGesture:(UITapGestureRecognizer *)recognizer;
- (void)handleSwipeGesture:(UISwipeGestureRecognizer *)recognizer;
- (void)preGroup;
- (void)nextGroup;
- (void)prePic;
- (void)nextPic;
- (void)showMenuView:(BOOL)show;
- (void)showImageBySwipeWithIndex:(NSInteger)index direction:(UISwipeGestureRecognizerDirection)direction;
- (void)showImageWithIndex:(NSInteger)index;
//初始化图片列表
- (void)initImageList;
- (void)setupPicInfo;
- (void)autoSwitchImage;

@end


@implementation DetailImageView

@synthesize delegate = _delegate;
@synthesize viewController = _viewController;
@synthesize imageSrollView = _imageSrollView;
@synthesize imageView = _imageView;
@synthesize infoScrollView = _infoScrollView;
@synthesize menuView = _menuView;
@synthesize curSelectedImageIndex = _curSelectedImageIndex;
@synthesize timer = _timer;
@synthesize colorHeadImage = _colorHeadImage;

@synthesize bgImageViewCount = _bgImageViewCount;
@synthesize labelCount = _labelCount;

- (void)dealloc {
    _delegate = nil;
    RELEASE_SAFELY(_labelCount);
    RELEASE_SAFELY(_bgImageViewCount);
    INVALIDATE_TIMER(_timer);
    RELEASE_SAFELY(_menuView);
    RELEASE_SAFELY(_imageView);
    RELEASE_SAFELY(_imageSrollView);
    RELEASE_SAFELY(_infoScrollView);
    RELEASE_SAFELY(_picture);
    RELEASE_SAFELY(_datasource);
    _viewController = nil;
    RELEASE_SAFELY(_colorHeadImage);
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
//        [self colorHeadImage];
        self.backgroundColor = [UIColor blackColor];//COLOR_RGB(52, 52, 52);
        
        self.curSelectedImageIndex = -1;
        _isAnimating = NO;
        _curOrientation = [UIApplication sharedApplication].statusBarOrientation;
        [self menuView];
        //双击，退出
        UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                                      action:@selector(handleTapGesture:)];
        doubleTapGestureRecognizer.numberOfTapsRequired = 2;
        doubleTapGestureRecognizer.delegate = self;
        [self addGestureRecognizer:doubleTapGestureRecognizer];
        
        //单击，隐藏菜单
        UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                                      action:@selector(handleTapGesture:)];
        singleTapGestureRecognizer.numberOfTapsRequired = 1;
        singleTapGestureRecognizer.delegate = self;
        [self addGestureRecognizer:singleTapGestureRecognizer];
        [singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer];
        
        
        //左右滑动手势
        UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc]
                                                                initWithTarget:self
                                                                action:@selector(handleSwipeGesture:)];
        leftSwipeGestureRecognizer.direction =UISwipeGestureRecognizerDirectionLeft;
        leftSwipeGestureRecognizer.delegate = self;
        [self addGestureRecognizer:leftSwipeGestureRecognizer];
        
        UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] 
                                                                 initWithTarget:self
                                                                 action:@selector(handleSwipeGesture:)];
        rightSwipeGestureRecognizer.direction =UISwipeGestureRecognizerDirectionRight;
        rightSwipeGestureRecognizer.delegate = self;
        [self addGestureRecognizer:rightSwipeGestureRecognizer];

    }
    return self;
}

- (void)initImageView
{
    self.imageView.frame = CGRectMake(0, kDefaultColorHeadHeight, self.bounds.size.width, kImageViewDefaultHeight*2.5);
    self.imageView.contentMode = UIViewContentModeCenter;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setContentWithSources:(NSArray *)sources picture:(PicModel *)picture fromSubject:(BOOL)fromSubject;
{
    self.picture = picture;
    self.datasource = sources;
    [self performSelector:@selector(initImageList) withObject:nil afterDelay:0.0];
}

- (void)initImageList 
{
    self.curSelectedImageIndex = 0;
    [self showImageWithIndex:self.curSelectedImageIndex];

}

#pragma mark - layout method
- (void)layoutSubviews 
{
    [super layoutSubviews];
    if (self.imageSrollView.zoomScale == 1.0) {
        
        [self resetImageViewSize];
    } else {
        
        self.imageSrollView.contentSize = CGSizeMake(MAX(self.imageSrollView.bounds.size.width,
                                                         self.imageView.frame.size.width),
                                                     MAX(self.imageSrollView.bounds.size.height,
                                                         self.imageView.frame.size.height));
        self.imageView.center = CGPointMake(self.imageSrollView.contentSize.width/2,
                                            self.imageSrollView.contentSize.height/2);
    }
    
    if (_curOrientation != [UIApplication sharedApplication].statusBarOrientation) {
        _curOrientation = [UIApplication sharedApplication].statusBarOrientation;
        [self setupPicInfo];
    }
}

#pragma mark - getter method
- (UIImageView *)colorHeadImage
{
    if (!_colorHeadImage)
    {
        _colorHeadImage = [[UIImageView alloc] initWithImage:IMGNAMED(@"bg_colorhead.png")];
        _colorHeadImage.frame = CGRectMake(0, 0, self.bounds.size.width, kDefaultColorHeadHeight);
        _colorHeadImage.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self addSubview:_colorHeadImage];
    }
    return _colorHeadImage;
}

- (UIView *)menuView {
    if (!_menuView) {
        _menuView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 40, self.bounds.size.width, kDefaultBottomBarHeight)];
        _menuView.backgroundColor = COLOR_RGB(26.0, 26.0, 26.0);//COLOR_RGB_BOTTOM;
        
        _menuView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
        _menuView.clipsToBounds = YES;
        
        
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        backButton.exclusiveTouch = YES;
        UIImage *image = IMGNAMED(@"btn_back.png");
        backButton.frame = CGRectMake(10, 
                                      floor((kDefaultBottomBarHeight-image.size.height)/2),
                                      image.size.width,
                                      image.size.height);
        [backButton setBackgroundImage:image forState:UIControlStateNormal];
        [backButton setBackgroundImage:IMGNAMED(@"btn_back_light.png") 
                              forState:UIControlStateHighlighted];
        [backButton addTarget:self action:@selector(backButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:backButton];
        
        CGFloat right = self.bounds.size.width-10;
        
        UIButton *topButton = [UIButton buttonWithType:UIButtonTypeCustom];
        topButton.exclusiveTouch = YES;
        topButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        image = IMGNAMED(@"btn_top.png");
        topButton.frame = CGRectMake(right-image.size.width,
                                     floor((kDefaultBottomBarHeight-image.size.height)/2),
                                     image.size.width,
                                     image.size.height);
        [topButton setBackgroundImage:image forState:UIControlStateNormal];
        [topButton setBackgroundImage:IMGNAMED(@"btn_top_light.png") 
                             forState:UIControlStateHighlighted];
        [topButton addTarget:self
                      action:@selector(topButtonPressed:)
            forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:topButton];
        right -= image.size.width + 10;
        /*
        UIButton *forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        forwardButton.exclusiveTouch = YES;
        forwardButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        image = IMGNAMED(@"btn_forward.png");
        forwardButton.frame = CGRectMake(right-image.size.width, 
                                         floor((kDefaultBottomBarHeight-image.size.height)/2),
                                         image.size.width,
                                         image.size.height);
        [forwardButton setBackgroundImage:image forState:UIControlStateNormal];
        [forwardButton setBackgroundImage:IMGNAMED(@"btn_forward_light.png")
                                 forState:UIControlStateHighlighted];
        [forwardButton addTarget:self action:@selector(forwardButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:forwardButton];
        
        right -= image.size.width+10;
        
        */
        UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        playButton.exclusiveTouch = YES;
        playButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        image = IMGNAMED(@"btn_play.png");
        playButton.frame = CGRectMake(right-image.size.width, 
                                      floor((kDefaultBottomBarHeight-image.size.height)/2),
                                      image.size.width, image.size.height);
        [playButton setBackgroundImage:image forState:UIControlStateNormal];
        [playButton setBackgroundImage:IMGNAMED(@"btn_play_light.png") 
                              forState:UIControlStateHighlighted];
        [playButton addTarget:self action:@selector(playButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:playButton];
        
        right -= image.size.width+10;
        
        UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        downloadButton.exclusiveTouch = YES;
        downloadButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        image = IMGNAMED(@"btn_download.png");
        downloadButton.frame = CGRectMake(right-image.size.width, 
                                          floor((kDefaultBottomBarHeight-image.size.height)/2),
                                          image.size.width, image.size.height);
        [downloadButton setBackgroundImage:image forState:UIControlStateNormal];
        [downloadButton setBackgroundImage:IMGNAMED(@"btn_download_light.png") 
                                  forState:UIControlStateHighlighted];
        [downloadButton addTarget:self action:@selector(downloadButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:downloadButton];
        
//        right -= image.size.width+10;
        
        [self addSubview:_menuView];
    }
    
    return _menuView;
}

- (UIScrollView *)imageSrollView {
    if (!_imageSrollView) {
        
        _imageSrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _imageSrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _imageSrollView.backgroundColor = [UIColor clearColor];
        _imageSrollView.delegate = self;
        _imageSrollView.showsVerticalScrollIndicator = NO;
        _imageSrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_imageSrollView];
        [self sendSubviewToBack:_imageSrollView];
    }
    return _imageSrollView;
}

- (MKImageView *)imageView {
    if (!_imageView) {
        _imageView = [[MKImageView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, kImageViewDefaultHeight)];
        _imageView.contentMode = UIViewContentModeCenter;
        _imageView.clipsToBounds = YES;
        
        _imageView.layer.borderWidth = 1.0;
        _imageView.layer.borderColor = [UIColor colorWithWhite:0.5 alpha:0.1].CGColor;
        
        [self.imageSrollView addSubview:_imageView];
    }
    return _imageView;
}

- (UIScrollView *)infoScrollView {
    if (!_infoScrollView) {
        _infoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - kDefaultBottomBarHeight - 120,
                                                                         self.bounds.size.width, 120)];
        _infoScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        _infoScrollView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        _infoScrollView.clipsToBounds = YES;
        
        [self addSubview:_infoScrollView];
        [self bringSubviewToFront:self.menuView];
    }
    return _infoScrollView;
}

- (UIImageView *)bgImageViewCount {
    if (!_bgImageViewCount) {
        UIImage *image = IMGNAMED(@"bg_counter.png");
        image = [image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:image.size.height/2];
        _bgImageViewCount = [[UIImageView alloc] initWithImage:image];
        _bgImageViewCount.hidden = YES;
        _bgImageViewCount.frame = CGRectMake(self.bounds.size.width-image.size.width-10,
                                             self.bounds.size.height-image.size.height-10,
                                             image.size.width, image.size.width);
        
        _bgImageViewCount.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
        
        [self insertSubview:_bgImageViewCount belowSubview:self.menuView];
    }
    
    return _bgImageViewCount;
}

- (UILabel *)labelCount {
    if (!_labelCount) {
        _labelCount = [[UILabel alloc] initWithFrame:[self.bgImageViewCount bounds]];
        _labelCount.backgroundColor = [UIColor clearColor];
        _labelCount.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _labelCount.font = FONT_NUMBER(30.0f);
        _labelCount.textColor = COLOR_RGB(255.0, 255.0, 255.0);
        _labelCount.textAlignment = NSTextAlignmentCenter;
        
        [self.bgImageViewCount addSubview:_labelCount];
    }
    
    return _labelCount;
}
 
#pragma mark - Utility method
- (void)showMenuView:(BOOL)show 
{    
    if (!show)
    {
        if (_delegate && [_delegate respondsToSelector:@selector(detailImageViewShowMenu:)])
        {
            [_delegate detailImageViewShowMenu:show];
        }
    }
    
    self.bgImageViewCount.hidden = show;
    
    [UIView animateWithDuration:0.25
                          delay:0.0 options:UIViewAnimationCurveEaseInOut|UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         //显示、隐藏菜单栏
                         CGRect frame = self.menuView.frame;
                         if (show) {
                             frame.origin.y = self.bounds.size.height - kDefaultBottomBarHeight;
                             self.infoScrollView.alpha = 1.0f;
                         } else {
                             frame.origin.y = self.bounds.size.height;
                             self.infoScrollView.alpha = 0.0f;
                         }
                         self.menuView.frame = frame;
                     } completion:^(BOOL finished) 
                        {
                            if (show)
                            {
                                if (_delegate && [_delegate respondsToSelector:@selector(detailImageViewShowMenu:)])
                                {
                                    [_delegate detailImageViewShowMenu:show];
                                }
                            }
                        }];
}

#pragma mark - UIAlertViewDelegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	switch (buttonIndex) {
		case 0:
			UIImageWriteToSavedPhotosAlbum(self.imageView.image,
                                           self,
                                           @selector(image:didFinishSavingWithError:contextInfo:),
                                           nil);
			break;
		default:
			break;
	}
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{

	if (error == nil){
//        [BUUtil showTipsView:@"图片已经保存到本地相册" atView:self];
	} else {
//        [BUUtil showTipsView:@"保存失败，请重试!" atView:self];
	}
}

#pragma mark - UIButton method
- (void)backButtonTapped:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(closeDetailImageView:)]) {
        [self.delegate closeDetailImageView:self];
    }
}

- (void)topButtonPressed:(id)sender
{
    [self.imageSrollView setContentOffset:CGPointMake(self.imageSrollView.contentOffset.x, 0) animated:YES];
    [self.infoScrollView setContentOffset:CGPointMake(self.infoScrollView.contentOffset.x, 0) animated:YES];
}

- (void)downloadButtonTapped:(id)sender {
    UIAlertView *alertView = nil;
    alertView = [[UIAlertView alloc] initWithTitle:nil
                                           message:@"是否保存图片到本地相册"
                                          delegate:self
                                 cancelButtonTitle:@"确定"
                                 otherButtonTitles:@"取消",nil];
    [alertView show];
}

- (void)playButtonTapped:(id)sender {
    INVALIDATE_TIMER(_timer);
    
    if ([self.picture.SinglePics count] < 2) {
        return;
    }
    
    [self autoSwitchImage];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:kImageSwitchInterval 
                                                  target:self 
                                                selector:@selector(autoSwitchImage) 
                                                userInfo:nil 
                                                 repeats:YES]; 
    
    [self showMenuView:NO]; 
}

- (void)forwardButtonTapped:(id)sender 
{
    if (_delegate && [_delegate respondsToSelector:@selector(willEnterOtherView:)])
    {
        [_delegate willEnterOtherView:self];
    }
    SinglePic *singPic = [self.picture.SinglePics objectAtIndex:self.curSelectedImageIndex];
    if (_delegate && [_delegate respondsToSelector:@selector(detailImageView:forwardPicture:singlePic:)]) {
        [_delegate detailImageView:self forwardPicture:self.imageView.image singlePic:singPic];
    }
}

- (void)preGroup {
    if (_isAnimating) {
        return;
    }
    
    NSInteger idx = [self.datasource indexOfObjectIdenticalTo:self.picture];
    
    if (idx > 0) {
        PicModel *picture = (PicModel *)[self.datasource objectAtIndex:idx-1];
        
        if (picture && picture.SinglePics && [picture.SinglePics count]>0) {
            self.picture = picture;
            self.curSelectedImageIndex = [self.picture.SinglePics count]-1;

            [self showImageBySwipeWithIndex:self.curSelectedImageIndex direction:UISwipeGestureRecognizerDirectionRight];
        }
    }
}

- (void)nextGroup {
    if (_isAnimating) {
        return;
    }
    
    NSInteger idx = [self.datasource indexOfObjectIdenticalTo:self.picture];
    
    if (idx < [self.datasource count]-1) {
        
        PicModel *picture = (PicModel *)[self.datasource objectAtIndex:idx+1];
        
        if (picture && picture.SinglePics && [picture.SinglePics count]>0) {
            self.picture = picture;
            
            self.curSelectedImageIndex = 0;

            [self showImageBySwipeWithIndex:self.curSelectedImageIndex direction:UISwipeGestureRecognizerDirectionLeft];

        }
    }
}

- (void)prePic {
    if (_isAnimating) {
        return;
    }
    if (self.curSelectedImageIndex > 0) {
        self.curSelectedImageIndex--;
        [self showImageBySwipeWithIndex:self.curSelectedImageIndex direction:UISwipeGestureRecognizerDirectionRight];
    } else {
        NSInteger idx = [self.datasource indexOfObjectIdenticalTo:self.picture];
        if (idx > 0 && idx < [self.datasource count]) {
            [self preGroup];
        } else if (idx == 0) {
            [self backButtonTapped:nil];
        }
    }
}

- (void)nextPic {
    if (_isAnimating) {
        return;
    }
    if (self.curSelectedImageIndex <[self.picture.SinglePics count]-1) {
        self.curSelectedImageIndex++;
        [self showImageBySwipeWithIndex:self.curSelectedImageIndex direction:UISwipeGestureRecognizerDirectionLeft];
    } else {
        NSInteger idx = [self.datasource indexOfObjectIdenticalTo:self.picture];
        if (idx >= 0 && idx < [self.datasource count]-1) {
            [self nextGroup];
        }
    }
}

- (void)autoSwitchImage 
{    
    if (self.curSelectedImageIndex == [self.picture.SinglePics count]-1)
    {
        NSInteger idx = [self.datasource indexOfObjectIdenticalTo:self.picture];
        
        if (idx >= [self.datasource count]-1) {
            self.picture = [self.datasource objectAtIndex:0];
        } 
        else
        {
            self.picture = [self.datasource objectAtIndex:idx+1];
        }
        self.curSelectedImageIndex = 0;
    }
    else 
    {
        self.curSelectedImageIndex++;
    }

    [self showImageWithIndex:self.curSelectedImageIndex];
}

- (void)setupPicInfo {
    
    if (self.curSelectedImageIndex >= 0 && self.curSelectedImageIndex < [self.picture.SinglePics count]) {
        SinglePic *singPic = [self.picture.SinglePics objectAtIndex:self.curSelectedImageIndex];
        
        self.labelCount.text = [NSString stringWithFormat:@"%d/%d",_curSelectedImageIndex+1,[self.picture.SinglePics count]];
        CGSize size = [self.labelCount sizeThatFits:CGSizeMake(CGFLOAT_MAX, 44)];
        
        CGRect frame = self.bgImageViewCount.frame;
        frame.size.width = (size.width+10)>44?(size.width+10):44;
        frame.origin.x = self.bounds.size.width-frame.size.width-10;
        self.bgImageViewCount.frame = frame;
        
        
        for (UIView *view in self.infoScrollView.subviews) {
            [view removeFromSuperview];
        }
        
        NSInteger top = 10;
        
        UILabel *indexLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        indexLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        indexLabel.font = FONT_NUMBER(20.0f);
        indexLabel.textColor = COLOR_RGB(221.0, 221.0, 221.0);
        indexLabel.numberOfLines = 0;
        indexLabel.backgroundColor = [UIColor clearColor];
        indexLabel.text = [NSString stringWithFormat:@"%d/%d",_curSelectedImageIndex+1,[self.picture.SinglePics count]];
        size = [indexLabel sizeThatFits:CGSizeMake(self.infoScrollView.bounds.size.width-20, MAXFLOAT)];
        indexLabel.frame = CGRectMake(self.infoScrollView.bounds.size.width-10-size.width,
                                      top,
                                      size.width,
                                      size.height);
        [self.infoScrollView addSubview:indexLabel];
        
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.font = FONT_CONTENT(20);
        titleLabel.textColor = COLOR_RGB(221.0, 221.0, 221.0);
        titleLabel.numberOfLines = 0;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = self.picture.title;
        size = [titleLabel sizeThatFits:CGSizeMake(self.infoScrollView.bounds.size.width-30-size.width, CGFLOAT_MAX)];
        titleLabel.frame = CGRectMake(10, top, size.width, size.height);
        
        [self.infoScrollView addSubview:titleLabel];
        
        top += size.height+5;
/*
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[NSDate date]timeIntervalSince1970]];
        NSString *time = [dateFormatter stringFromDate:date];
        
        UILabel *authorLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        authorLabel.font = FONT_CONTENT(10);
        authorLabel.textColor = COLOR_RGB(221.0, 221.0, 221.0);
        authorLabel.numberOfLines = 1;
        authorLabel.backgroundColor = [UIColor clearColor];
        NSString *string = nil;
        string = [NSString stringWithFormat:@"%@",time];
        authorLabel.text = string;
        size = [authorLabel sizeThatFits:CGSizeMake(self.infoScrollView.bounds.size.width-20,
                                                    MAXFLOAT)];
        authorLabel.frame = CGRectMake(10, top, size.width, size.height);
        
        [self.infoScrollView addSubview:authorLabel];
        
        top += size.height+10;
        */
        NSString *text = singPic.intro;
        
        if (text && [text length]>0) {
            UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, top, self.infoScrollView.bounds.size.width-20, 1)];
            lineImage.backgroundColor = COLOR_RGB(77, 77, 77);
            [self.infoScrollView addSubview:lineImage];
            top += 5;
            
            UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectZero];
            contentLabel.font = FONT_CONTENT(13);
            contentLabel.textColor = COLOR_RGB(221.0, 221.0, 221.0);
            contentLabel.numberOfLines = 0;
            contentLabel.backgroundColor = [UIColor clearColor];
            contentLabel.text = text;
            size = [contentLabel sizeThatFits:CGSizeMake(self.infoScrollView.bounds.size.width-20, MAXFLOAT)];
            contentLabel.frame = CGRectMake(10, top, size.width, size.height);
            
            [self.infoScrollView addSubview:contentLabel];
            
            top += size.height+10;
        }

        CGFloat maxHeight = 100;
        if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) {
            maxHeight = 120;
        }
        CGRect f = self.infoScrollView.frame;
        f.size.height = top>maxHeight?maxHeight:top;
        f.origin.y = self.bounds.size.height - kDefaultBottomBarHeight - f.size.height;
        self.infoScrollView.frame = f;
        self.infoScrollView.contentSize = CGSizeMake(self.infoScrollView.bounds.size.width, top);
        [self.infoScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    
}

#pragma mark - UIScrollView Delegate method
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    self.imageSrollView.contentSize = CGSizeMake(MAX(self.imageSrollView.bounds.size.width,
                                                     self.imageView.frame.size.width),
                                                 MAX(self.imageSrollView.bounds.size.height,
                                                     self.imageView.frame.size.height));
    self.imageView.center = CGPointMake(self.imageSrollView.contentSize.width/2,
                                        self.imageSrollView.contentSize.height/2);
}

- (void)resetImageViewSize {
    
    CGSize imageSize = CGSizeZero;
    if ( (imageSize.width <=0 || imageSize.height <= 0) &&
        self.imageView.image != nil &&
        self.imageView.image.size.width > 0 &&
        self.imageView.image.size.height > 0)
    {
        imageSize = self.imageView.image.size;
    }
    
    CGFloat maxScaleRatio = 2.0;
    CGSize size = self.imageSrollView.bounds.size;
    
    if (imageSize.width > size.width ||
        imageSize.height > size.height) {
        CGFloat ratio1 = imageSize.width/size.width;
        CGFloat ratio2 = imageSize.height/size.height;
        
        if (ratio1 > ratio2) {
            imageSize.height /= ratio1;
            imageSize.width = size.width;
            maxScaleRatio = ratio1*2;
        } else {
            imageSize.width /= ratio2;
            imageSize.height = size.height;
            maxScaleRatio = ratio2*2;
        }
    }
    
    self.imageSrollView.minimumZoomScale = 0.5;
    self.imageSrollView.zoomScale = 1.0;
    self.imageSrollView.maximumZoomScale = maxScaleRatio;
    self.imageSrollView.contentSize = CGSizeMake(MAX(self.imageSrollView.bounds.size.width,
                                                     imageSize.width),
                                                 MAX(self.imageSrollView.bounds.size.height,
                                                     imageSize.height));
    
    self.imageView.frame = CGRectMake(floor((self.imageSrollView.contentSize.width-imageSize.width)/2),
                                      floor((self.imageSrollView.contentSize.height-imageSize.height)/2),
                                      imageSize.width,
                                      imageSize.height);
    
}

#pragma mark - UIGestureRecognizer method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
       shouldReceiveTouch:(UITouch *)touch {
    
    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    
    if ([touch.view isDescendantOfView:self.menuView]) {
        return NO;
    }
    
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([gestureRecognizer isKindOfClass:[UISwipeGestureRecognizer class]] &&
        [otherGestureRecognizer.view isKindOfClass:[UIScrollView class]] &&
        ![otherGestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        UIScrollView *scrollView = (UIScrollView *)otherGestureRecognizer.view;
        if (scrollView.contentOffset.x <= 0 ||
            scrollView.contentOffset.x >= (scrollView.contentSize.width-scrollView.bounds.size.width)) {
            return YES;
        }
    }
    
    return NO;
}

- (void)handleTapGesture:(UITapGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        switch (recognizer.numberOfTapsRequired) {
            case 1:
                
                [self showMenuView:self.menuView.frame.origin.y >= self.bounds.size.height];
                INVALIDATE_TIMER(_timer);
                break;
            case 2:

                if (self.imageSrollView.zoomScale == 1.0) {
                    INVALIDATE_TIMER(_timer);
                    [self backButtonTapped:nil];
                } else {
                    [UIView animateWithDuration:0.25
                                          delay:0.0f options:UIViewAnimationCurveEaseInOut
                                     animations:^{
                                         [self resetImageViewSize];
                                     }
                                     completion:NULL];
                }
                
                break;
                
            default:
                break;
        }
    }
    
}

- (void)handleSwipeGesture:(UISwipeGestureRecognizer *)recognizer {
    
    if (recognizer.state == UIGestureRecognizerStateRecognized) {
        if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
            [self nextPic];
        } else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
            [self prePic];
        }
    }
}

- (void)showImageBySwipeWithIndex:(NSInteger)index direction:(UISwipeGestureRecognizerDirection)direction {
    if (index < 0 || index >= [self.picture.SinglePics count]) {
        return;
    }
    
    CATransition *transition = [CATransition animation];
    transition.duration = .5;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.removedOnCompletion = YES;
    transition.delegate = self;
    if (direction == UISwipeGestureRecognizerDirectionLeft) {
        transition.subtype = kCATransitionFromRight;
    } else {
        transition.subtype = kCATransitionFromLeft;
    }
    [self.imageSrollView.layer addAnimation:transition forKey:nil];

    _isAnimating = YES;
    
    [self initImageView];
    SinglePic *singPic = [self.picture.SinglePics objectAtIndex:index];
    __block MKImageView *wImageView = self.imageView;
    __block DetailImageView *wSelf = self;
    [self.imageView setImageWithURL:[NSURL URLWithString:singPic.small] placeholderImage:IMGNAMED(@"bg_image_placeholder.png") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {


        wImageView.contentMode = UIViewContentModeScaleAspectFill;
        CABasicAnimation *opAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
        opAnim.duration = .5;
        opAnim.fromValue = [NSNumber numberWithFloat:0.5];
        opAnim.toValue = [NSNumber numberWithFloat:1.0];
        opAnim.removedOnCompletion = YES;
        [opAnim setValue:@"fadeInAnim" forKey:@"moveAnim"];
        opAnim.fillMode = kCAFillModeForwards;

        [wImageView.layer addAnimation:opAnim forKey:@"moveAnim"];
        [wSelf resetImageViewSize];
        [wSelf setupPicInfo];
    }];
}

- (void)showImageWithIndex:(NSInteger)index 
{
    if (index < 0 || index >= [self.picture.SinglePics count])
    {
        return;
    }
    
    [self.imageView.layer removeAnimationForKey:@"Fade_Transition"];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 1;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    transition.removedOnCompletion = YES;
    transition.delegate = self;
    [self.imageSrollView.layer addAnimation:transition forKey:@"Fade_Transition"];
    
    _isAnimating = YES;
    
    [self initImageView];
    SinglePic *singPic = [self.picture.SinglePics objectAtIndex:index];

    __block MKImageView *wImageView = self.imageView;
    __block DetailImageView *wSelf = self;
    [self.imageView setImageWithURL:[NSURL URLWithString:singPic.small] placeholderImage:IMGNAMED(@"bg_image_placeholder.png") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {


        wImageView.contentMode = UIViewContentModeScaleAspectFill;
        CABasicAnimation *opAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
        opAnim.duration = .5;
        opAnim.fromValue = [NSNumber numberWithFloat:0.5];
        opAnim.toValue = [NSNumber numberWithFloat:1.0];
        opAnim.removedOnCompletion = YES;
        [opAnim setValue:@"fadeInAnim" forKey:@"moveAnim"];
        opAnim.fillMode = kCAFillModeForwards;

        [wImageView.layer addAnimation:opAnim forKey:@"moveAnim"];
        [wSelf resetImageViewSize];
        [wSelf setupPicInfo];

    }];
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    _isAnimating = NO;
}
@end
